<template>
  <div>
    <el-container style="flex-wrap: wrap;">
      <!-- 头部 -->
      <!-- 头部导航栏 -->
      <BreadHeader></BreadHeader>
      <XPannel>
        <template v-slot:header>
          <span>库存管理</span>
          <el-button
            type="primary"
            style="float: right; padding: 10px 20px; margin-left: 15px"
            @click="addproduct"
            >添加库存</el-button
          >
          <!-- 库存添加的抽屉-- -->
          <el-drawer
            title="灯泡库存添加区"
            :visible.sync="draweradd"
            ref="drawer"
            :show-close="true"
            style="text-align: center"
          >
            <el-form
              :model="numberValidateForm"
              ref="numberValidateForm"
              label-width="100px"
              class="demo-ruleForm"
            >
              <el-form-item
                label="商品类型"
                prop="product_type"
                style="width: 80%; margin: auto"
                :rules="[
            { required: true, message: '请选择商品类型', trigger: 'change' }
          ],"
              >
                <el-select
                  v-model="numberValidateForm.product_type"
                  placeholder="请选择商品类型"
                  style="width: 300px"
                >
                  <el-option label="灯泡" :value="1"></el-option>
                  <el-option label="水龙头" :value="2"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="当前剩余"
                style="width: 80%; margin: 20px auto"
              >
                <span style="color: red; font-size: 25px">{{
                  total_product
                }}</span>
              </el-form-item>
              <el-form-item
                label="新采购"
                prop="product_add"
                :rules="[
                  { required: true, message: '商品采购量不能为空' },
                  { type: 'number', message: '商品采购量必须为数字值' },
                ]"
                style="width: 80%; margin: 20px auto"
              >
                <el-input
                  v-model.number="numberValidateForm.product_add"
                  autocomplete="off"
                  style="width: 300px"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="总库存"
                prop="product_all"
                :rules="[
                  { required: true, message: '商品添加量不能为空' },
                  { type: 'number', message: '商品添加量必须为数字值' },
                ]"
                style="width: 80%; margin: auto; margin-bottom: 20px"
              >
                <el-input
                  v-model.number="numberValidateForm.product_all"
                  autocomplete="off"
                  style="width: 300px"
                ></el-input>
              </el-form-item>
              <!-- <el-form-item style="width: 300px; margin: 20px auto"> -->
              <el-button
                type="primary"
                @click="submitForm('numberValidateForm')"
                >提交</el-button
              >
              <el-button @click="resetForm('numberValidateForm')" style=""
                >重置</el-button
              >
              <!-- </el-form-item> -->
            </el-form>
          </el-drawer>
        </template>

        <template v-sot:default>
          <!-- 搜索功能----- -->
          <el-row style="margin: 5px 0" :gutter="20">
            <el-col :span="1.8" style="padding: 0 0; margin: 0 10px">
              <template>
                <p style="color: #303133; font-size: 16px; line-height: 40px">
                  搜索栏：
                </p>
              </template>
            </el-col>
            <el-col :span="4" style="padding: 0 0">
              <el-input
                placeholder="请输入原有数量"
                v-model="seacherold"
                clearable
                style="width: 230px"
              >
              </el-input>
            </el-col>
            <el-col :span="7" style="padding: 0 0; margin: 0 0px">
              <el-date-picker
                v-model="value2"
                type="datetimerange"
                :picker-options="pickerOptions"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="right"
                style="width: 400px"
              >
              </el-date-picker>
            </el-col>
            <el-col :span="4" style="padding: 0 0; margin: 0 0px">
              <el-select
                v-model="seachernew"
                placeholder="请选择当前数量范围"
                style="width: 230px"
                clearable
              >
                <el-option label="大于10" :value="10"></el-option>
                <el-option label="大于20" :value="20"></el-option>
                <el-option label="大于30" :value="30"></el-option>
              </el-select>
            </el-col>
            <el-col :span="4" style="padding: 0 0; margin: 0 0px">
              <el-select
                v-model="seachpname"
                placeholder="请选择商品名称"
                style="width: 230px"
                clearable
              >
                <el-option 
                v-for="item in product_name_list"
                :key="item.id"
                :label="item.productname" 
                :value="item.id"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="2" :offset="3" style="margin-left: 0px">
              <el-button
                type="primary"
                @click="searchusers"
                style="padding: 12px 15px"
              >
                <i class="el-icon-search"></i>搜索
              </el-button>
            </el-col>
          </el-row>
          <!-- 库存列表 -->
          <el-table
            ref="multipleTable"
            :data="inventlist"
            tooltip-effect="dark"
            style="width: 100%; margin: 15px auto"
            @selection-change="handleSelectionChange"
            height="450"
            border
          >
            <el-table-column label="全选" type="selection" width="55">
            </el-table-column>
            <el-table-column prop="id" label="ID" width="50"> </el-table-column>
            <el-table-column prop="oldnumber" label="原来数量" width="150">
            </el-table-column>
            <el-table-column prop="addnumber" label="添加数量" width="150">
            </el-table-column>
            <el-table-column prop="usenumber" label="使用数量" width="150">
            </el-table-column>
            <el-table-column prop="newnumber" label="现有数量" width="150">
            </el-table-column>
            <el-table-column prop="product_name" label="产品名称" width="150">
            </el-table-column>
            <!-- repairetype -->
            <el-table-column prop="caozuo" label="操作">
              <template #default="scope">
                <el-button
                  @click="xiugaiobtain(scope.row)"
                  type="primary"
                  style="margin-left: 16px; padding: 5px 10px"
                >
                  <i class="el-icon-edit"></i>
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  @click="open(scope.row)"
                  style="padding: 5px 10px"
                  ><i class="el-icon-delete"></i> 删除</el-button
                >
                <!-- 人员修改的drawer -->
                <el-drawer
                  title="库存修改区"
                  :visible.sync="drawer"
                  :show-close="true"
                  style="text-align: center"
                >
                  <el-form
                    :model="edutruleForm"
                    ref="edutruleForm"
                    label-width="100px"
                    class="demo-ruleForm"
                  >
                    <el-form-item
                      label="产品名称"
                      style="margin: 20px; width: 80%; margin: 20px auto"
                    >
                      <span>{{ edutruleForm.type_name }}</span>
                    </el-form-item>
                    <el-form-item
                      label="原有数量"
                      prop="oldnumber"
                      style="margin: 20px; width: 80%; margin: 20px auto"
                    >
                      <el-input-number
                        v-model="edutruleForm.oldnumber"
                        :disabled="true"
                        :step="1"
                        style="width: 300px; display: block"
                      ></el-input-number>
                    </el-form-item>
                    <el-form-item
                      label="添加数量"
                      prop="addnumber"
                      style="margin: 20px; width: 80%; margin: 20px auto"
                    >
                      <el-input-number
                        v-model="edutruleForm.addnumber"
                        :step="1"
                        style="width: 300px; display: block"
                      ></el-input-number>
                    </el-form-item>
                    <el-form-item
                      label="使用数量"
                      prop="usenumber"
                      style="margin: 20px; width: 80%; margin: 20px auto"
                    >
                      <el-input-number
                        v-model="edutruleForm.usenumber"
                        :disabled="true"
                        :step="1"
                        style="width: 300px; display: block"
                      ></el-input-number>
                    </el-form-item>
                    <el-form-item
                      label="现存数量"
                      prop="newnumber"
                      style="margin: 20px; width: 80%; margin: 20px auto"
                    >
                      <el-input-number
                        v-model="edutruleForm.newnumber"
                        :step="1"
                        style="width: 300px; display: block"
                      ></el-input-number>
                    </el-form-item>
                  </el-form>

                  <el-button
                    type="success"
                    @click="submit('edutruleForm')"
                    style="padding: 10px 20px; margin: 5px"
                    >确认修改</el-button
                  >
                  <el-button
                    type="info"
                    @click="reset('edutruleForm')"
                    style="padding: 10px 20px; margin: 5px"
                    >重置已填</el-button
                  >
                </el-drawer>
              </template>
            </el-table-column>
          </el-table>
          <!-- 批量操作 -->
          <div class="piliang" style="width: 300px; background: #ffffff">
            <el-button
              type="danger"
              @click="batchDelete"
              style="padding: 10px 15px; margin: 5px 0px"
              >批量删除</el-button
            >
            <el-button
              @click="toggleSelection()"
              type="primary"
              style="padding: 10px 15px; margin: 5px 10px"
              >取消选择</el-button
            >
            <!-- <el-button @click="clearSelection">取消批量</el-button> -->
          </div>
          <!-- 页码显示 -->
          <div
            class="block"
            style="padding: 20px; max-width: 600px; margin: auto"
          >
            <el-pagination
              :page-sizes="[5, 10, 15, 20]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalUsers"
              @size-change="handleChangeSize"
              @current-change="handleCurrentChange"
            >
            </el-pagination>
          </div>
        </template>
      </XPannel>
    </el-container>
  </div>
</template>

<script>
import http from "@/api/http";
import BreadHeader from "@/components/BreadHeader.vue";
import XPannel from "@/components/XPannel.vue";
import { mapState } from "vuex";

export default {
  components: {
    XPannel,
    BreadHeader
  },
  computed: {
    ...mapState(["name", "picture"]),
    userName() {
      return this.name;
    },
    userPicture() {
      return this.picture;
    },
  },
  data() {
    return {
      draweradd: false,
      inventlist: [],
      seacherold: null,
      value2: "",
      seachernew: null,
      seachpname: "",
      totalUsers: 0, //总数
      pageSize: 5, //每页条数
      pageNum: 1, //当前页码
      numberValidateForm: {
        product_add: null,
        product_all: 0,
        product_type: null,
      },
      edutruleForm: {
        oldnumber: 0,
        addnumber: 0,
        newnumber: 0,
        usenumber: 0,
        type: null,
        type_name: null,
      },
      total_deng: null,
      total_shui: null,
      total_product: 0,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      xiugaiobtainuid: null,
      drawer: false,
      product_name_list: [],
    };
  },
  methods: {
    // 库存商品名称列表显示的方法
    inventlist_namefn() {
      http
        .get("/kucun/product_list_all")
        .then((response) => {
          console.log(response.data);
          // 如果您想要整个item对象，那么不需要在map中只返回item.productname
          this.product_name_list = response.data.map((item) => item); // 保留整个对象
          // 如果您只需要productname字段，那么应该这样创建一个新数组
          // this.product_name_list = response.data.map(item => item.productname);
          console.log(this.product_name_list)
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 页码设置
    handleChangeSize(data) {
      this.pageSize = data;
      const isSeacheroldDefault = this.seacherold === null;
      const isValue2Default = this.value2 === "";
      const isSeachernewDefault = this.seachernew === null;
      const isSeachpnameDefault = this.seachpname === "";

      const isAllDefaults =
        isSeacheroldDefault &&
        isValue2Default &&
        isSeachernewDefault &&
        isSeachpnameDefault;

      if (isAllDefaults) {
        // 如果所有字段都是初始值，则调用inventlistfn
        this.inventlistfn();
      } else {
        this.searchusers();
      }
    },
    handleCurrentChange(data) {
      this.pageNum = data;
      const isSeacheroldDefault = this.seacherold === null;
      const isValue2Default = this.value2 === "";
      const isSeachernewDefault = this.seachernew === null;
      const isSeachpnameDefault = this.seachpname === "";

      const isAllDefaults =
        isSeacheroldDefault &&
        isValue2Default &&
        isSeachernewDefault &&
        isSeachpnameDefault;

      if (isAllDefaults) {
        // 如果所有字段都是初始值，则调用inventlistfn
        this.inventlistfn();
      } else {
        this.searchusers();
      }
    },
    // 商品添加的接口
    addproductfn() {},
    // 添加抽屉中的提交重置按钮--灯泡
    submitForm(formName) {
      const timestamp = Date.now();
      const date = new Date(timestamp);
      // 使用toLocaleDateString和toLocaleTimeString方法，它们提供了一种更简洁的方式来格式化日期和时间：
      // 格式化日期
      const formattedDate = date.toLocaleDateString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
      });

      // 格式化时间
      const formattedTime = date.toLocaleTimeString("zh-CN", {
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
        hour12: false, // 24小时制
      });

      // 拼接日期和时间
      const fullDateTime = `${formattedDate} ${formattedTime}`;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          http
            .post("/kucun/change/", {
              type: this.numberValidateForm.product_type,
              oldnumber: this.total_product,
              addnumber: this.numberValidateForm.product_add,
              subtime: fullDateTime,
            })
            .then((response) => {
              console.log(response);
            })
            .catch((error) => {
              console.log(error);
            });
          this.draweradd = false;
          this.$message({
            message: "恭喜你，库存添加成功！",
            type: "success",
          });
        } else {
          console.log("添加失败!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    open(row) {
      console.log(row);
    },
    // 批量删除
    batchDelete() {},
    // 批量取消
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    // 全选按钮
    handleSelectionChange(val) {
      this.selected = val;
      console.log(this.selected);
    },
    // 库存的搜索方法--代办
    searchusers() {
      http
        .get("/kucun/search", {
          params: {
            oldnumber: this.seacherold,
            time_range: this.value2,
            newnumber: this.seachernew,
            type: this.seachpname,
            page: this.pageNum,
            page_size: this.pageSize,
          },
        })
        .then((response) => {
          console.log(response);
          this.inventlist = response.data;
          this.totalUsers = response.total;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 库存添加的方法--代办
    addproduct() {
      this.draweradd = true;
    },
    // 库存列表显示的方法
    inventlistfn() {
      http
        .get("/kucun/list", {
          params: {
            page: this.pageNum,
            page_size: this.pageSize,
          },
        })
        .then((response) => {
          console.log(response);
          console.log(response.data);
          this.totalUsers = response.data.totalNum;
          this.inventlist = response.data.list;
          this.total_deng = response.data.total_deng;
          this.total_shui = response.data.total_shui;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 修改--获取数据
    xiugaiobtain(row) {
      this.drawer = true;
      console.log(row.id);
      let editid = row.id;
      http
        .get("kucun/edit/" + editid)
        .then((response) => {
          console.log(response);
          this.xiugaiobtainuid = response.data[0].id;
          this.edutruleForm.oldnumber = response.data[0].oldnumber;
          this.edutruleForm.addnumber = response.data[0].addnumber;
          this.edutruleForm.newnumber = response.data[0].newnumber;
          this.edutruleForm.usenumber = response.data[0].usenumber;
          this.edutruleForm.type = response.data[0].type;
          this.edutruleForm.type_name = response.data[0].productname;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 重置修改已填
    reset(formName) {
      this.$refs[formName].resetFields();
    },
    // 修改--保存数据
    submit() {
      http
        .post("/kucun/save_edit/" + this.xiugaiobtainuid, {
          oldnumber: this.edutruleForm.oldnumber,
          addnumber: this.edutruleForm.addnumber,
          usenumber: this.edutruleForm.usenumber,
          newnumber: this.edutruleForm.newnumber,
        })
        .then((response) => {
          console.log(response);
          this.drawer = false;
          this.$message({
            message: "恭喜你，库存修改成功！",
            type: "success",
          });
        })
        .catch((error) => {
          console.log(error);
        });
    },
  },
  created() {
    this.inventlistfn();
    this.inventlist_namefn();
  },
  watch: {
    "numberValidateForm.product_type"(newvalue) {
      if (newvalue == 1) {
        this.total_product = this.total_deng;
      }
      if (newvalue == 2) {
        this.total_product = this.total_shui;
      }
    },
  },
};
</script>

<style scoped>
</style>